﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Transactions;
using System.Windows;

using BLToolkit.Data;
using BLToolkit.Data.DataProvider;
using BLToolkit.DataAccess;

using EMan.Common.EnterpriseStructure;
using EMan.DAL.Firebird;

using FirebirdSql.Data.FirebirdClient;

using Server.FunctionalTests.Dal.Helpers;


namespace EManManagementConsole
{
  /// <summary>
  /// Interaction logic for MainWindow.xaml
  /// </summary>
  public partial class MainWindow
  {
    public MainWindow()
    {
      InitializeComponent();
    }

    private void ServerDebugButton_OnClick( object sender, RoutedEventArgs e )
    {
      StartEManServer( "debug" );
    }

    private void ServerReleaseButton_OnClick( object sender, RoutedEventArgs e )
    {
      StartEManServer( "release" );
    }

    private void StartEManServer( string subDirectory )
    {
      try
      {
        var directory = ConfigurationManager.AppSettings[ "EManServerPath" ];
        directory = Path.Combine( directory, subDirectory );
        new Process
          {
            StartInfo =
              new ProcessStartInfo( Path.Combine( directory, ConfigurationManager.AppSettings[ "EManServerFile" ] ) )
          }.
          Start();
      }
      catch( Exception exc )
      {
        MessageBox.Show( this, exc.Message, exc.GetType().Name, MessageBoxButton.OK, MessageBoxImage.Error );
      }
    }

    private void ClientDebugButton_OnClick( object sender, RoutedEventArgs e )
    {
      StartEManClient( "Debug" );
    }

    private void ClientReleaseButton_OnClick( object sender, RoutedEventArgs e )
    {
      StartEManClient( "Release" );
    }

    private void StartEManClient( string subDirectory )
    {
      StartProgram( subDirectory, "EManClientPath", "EManClientFile" );
    }

    private void StartProgram( string subDirectory, string pathKey, string fileKey )
    {
      try
      {
        var directory = ConfigurationManager.AppSettings[ pathKey ];
        directory = Path.Combine( directory, subDirectory );
        new Process
          {StartInfo = new ProcessStartInfo( Path.Combine( directory, ConfigurationManager.AppSettings[ fileKey ] ) )}.
          Start();
      }
      catch( Exception exc )
      {
        MessageBox.Show( this, exc.Message, exc.GetType().Name, MessageBoxButton.OK, MessageBoxImage.Error );
      }
    }

    private void DeployEmptyDatabaseButton_OnClick( object sender, RoutedEventArgs e )
    {
      DeployDatabase( CreateAndFillDatabase, false );
    }

    private void DeployDevelopmentDatabaseButton_OnClick( object sender, RoutedEventArgs e )
    {
      DeployDatabase( CreateAndFillDatabase, true );
    }

    private  void DeployDatabase(Action<string, string, bool, bool> deployDatabaseAction, bool fill)
    {
      try
      {
        _deployEmptyDatabaseButton.IsEnabled = false;
        _deployDevDatabaseButton.IsEnabled = false;

        var databaseDirectory = Path.GetFullPath( ConfigurationManager.AppSettings[ "DatabaseDirectory" ] );
        var databaseFilePath = Path.Combine( databaseDirectory, ConfigurationManager.AppSettings[ "DatabaseFileName" ] );
        File.Delete( databaseFilePath );
        _deployingStatus.Text = "Database was deleted. Deploying...";

        deployDatabaseAction( Path.Combine( databaseDirectory, ConfigurationManager.AppSettings[ "ScriptFileName" ] ),
                        databaseFilePath, false, fill );
        _deployingStatus.Text = "Database was deployed at " + DateTime.Now + " to " + databaseFilePath;
      }
      catch( Exception exc )
      {
        MessageBox.Show( this, string.Format("{0}{1}{2}", exc.Message, Environment.NewLine, exc.StackTrace ), exc.GetType().Name, MessageBoxButton.OK, MessageBoxImage.Error );
        
      }
      finally
      {
        _deployEmptyDatabaseButton.IsEnabled = true;
        _deployDevDatabaseButton.IsEnabled = true;
      }
    }

    private void CreateAndFillDatabase( string createScriptFilePath, string databaseFilePath, bool embeded, bool fill )
    {
      try
      {
        var connectionString = FbDatabase.DeployDatabase( createScriptFilePath, databaseFilePath, embeded );

        if(fill)
        {
          IEnumerable< Job > jobs;
          IEnumerable< Employee > employees;
          IEnumerable< Department > departments;
          CreateData( out jobs, out departments, out employees );

          using( var ts = new TransactionScope() )
          {
            using(var departmentDalc = DataAccessor.CreateInstance< DepartmentDalc >( new DbManager( new FdpDataProvider(), connectionString ) ) )
              foreach( var departement in departments )
                departmentDalc.Insert( departement );

            using( var jobDalc = DataAccessor.CreateInstance< JobDalc >( new DbManager( new FdpDataProvider(), connectionString ) ) )
              foreach( var job in jobs )
                jobDalc.Insert( job );

            using( var employeeDalc = DataAccessor.CreateInstance<EmployeeDalc>(new DbManager( new FdpDataProvider(), connectionString )))
              foreach( var employee in employees )
                employeeDalc.Insert( employee );

            ts.Complete();}
        }
      }
      finally
      {
        FbConnection.ClearAllPools();
      }
    }

    private static void CreateData(out IEnumerable<Job> jobs, out IEnumerable<Department> departments, out IEnumerable<Employee> employees )
    {
      
      var director = new Job( "Director" );
      var accounter = new Job( "Accounter" );
      var itAdmin = new Job( "IT Administator" );
      var worker = new Job( "Worker" );
      jobs = new List< Job > {director, accounter, itAdmin, worker};


      var topDepartment = new Department( "Top" );
      var accounting = new Department( "Accounting" );
      var itDepartment = new Department( "IT" );
      var resharper = new Department( "ReSharper" );
      var dotTrace = new Department( "dotTrace" );
      departments = new List< Department >{topDepartment, accounting, itDepartment, resharper, dotTrace};
      
      employees = new List<Employee>{
        new Employee( director, topDepartment, "Pan", "Ilya", "Vitrischak" ),
        new Employee( accounter, accounting, "Glavbuh", "Galina", "Petrovna" ),
        new Employee( accounter, accounting, "Buh", "Marina", "Vladimirovna" ),
        new Employee( itAdmin, itDepartment, "Pashtet", "Pachtet", "Pavlegovich" ),
        new Employee( itAdmin, itDepartment, "Zhukov", "Sergey", "Zhukov" ),
        new Employee( itAdmin, itDepartment, "Sizov", "Andrey", "Sizov" ),

        new Employee( worker, dotTrace, "Большой", "Большеляускас", "Каустеляйкас" ),
        new Employee( worker, dotTrace, "Скляр", "Сергей", "Скляренко" ),
        new Employee( worker, dotTrace, "Олег", "Олег", "Моховой" ),
        
        new Employee( worker, resharper, "Sanya", "Alexander", "Pepin" ),
        new Employee( worker, resharper, "Sanych", "Alexander", "Vorozhtsov" ),
        new Employee( worker, resharper, "Ed.ward", "Ed", "Ward" ),
      };
    }
  }
}